<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="couponName">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['coupon:coupons:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['coupon:coupons:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['coupon:coupons:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['coupon:coupons:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Document"
          @click="handleAllReceiveRecord"
        >领取记录</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="优惠券名称" align="center" prop="couponName" />
      <el-table-column label="优惠券类型" align="center" prop="couponType" />
      <el-table-column label="面额" align="center" prop="amount" />
      <el-table-column label="发放总量" align="center" prop="issueCount" />
      <el-table-column label="限领数量" align="center" prop="takeLimit" />
      <el-table-column label="消费门槛" align="center" prop="consumeThreshold" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="small">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="已领取数量" align="center" prop="receivedCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button link type="success" icon="Document" @click="handleReceiveRecord(scope.row)">领取记录</el-button>
          <el-button link type="danger" icon="Close" @click="handleClose(scope.row)" v-if="scope.row.status === 'ACTIVE'">关闭</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
<!--    <el-dialog :title="title" v-model="open" width="500px" append-to-body>-->
<!--      <el-form ref="couponsRef" :model="form" :rules="rules" label-width="80px">-->
<!--        <el-form-item label="活动名称" prop="activityName">-->
<!--          <el-input v-model="form.activityName" placeholder="请输入活动名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="优惠券名称" prop="couponName">-->
<!--          <el-input v-model="form.couponName" placeholder="请输入优惠券名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="面额" prop="amount">-->
<!--          <el-input v-model="form.amount" placeholder="请输入面额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="发放总量" prop="issueCount">-->
<!--          <el-input v-model="form.issueCount" placeholder="请输入发放总量" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="每人限领数量" prop="takeLimit">-->
<!--          <el-input v-model="form.takeLimit" placeholder="请输入每人限领数量" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="范围描述" prop="scopeDesc">-->
<!--          <el-input v-model="form.scopeDesc" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="消费门槛" prop="consumeThreshold">-->
<!--          <el-input v-model="form.consumeThreshold" placeholder="请输入消费门槛" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="有效期开始时间" prop="startTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.startTime"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择有效期开始时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="有效期结束时间" prop="endTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.endTime"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择有效期结束时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="逻辑删除" prop="isDeleted">-->
<!--          <el-input v-model="form.isDeleted" placeholder="请输入逻辑删除" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="已领取数量" prop="receivedCount">-->
<!--          <el-input v-model="form.receivedCount" placeholder="请输入已领取数量" />-->
<!--        </el-form-item>-->
<!--        <el-divider content-position="center">优惠券-商品关联（scope_type=PRODUCT时生效）信息</el-divider>-->
<!--        <el-row :gutter="10" class="mb8">-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" icon="Plus" @click="handleAddCouponProduct">添加</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" icon="Delete" @click="handleDeleteCouponProduct">删除</el-button>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-table :data="couponProductList" :row-class-name="rowCouponProductIndex" @selection-change="handleCouponProductSelectionChange" ref="couponProduct">-->
<!--          <el-table-column type="selection" width="50" align="center" />-->
<!--          <el-table-column label="序号" align="center" prop="index" width="50"/>-->
<!--        </el-table>-->
<!--      </el-form>-->
<!--      <template #footer>-->
<!--        <div class="dialog-footer">-->
<!--          <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--          <el-button @click="cancel">取 消</el-button>-->
<!--        </div>-->
<!--      </template>-->
<!--    </el-dialog>-->
  </div>
</template>

<script setup name="Coupons">
import { listCoupons, getCoupons, delCoupons, addCoupons, updateCoupons } from "@/api/coupon/coupons"
import { useRouter } from 'vue-router'
const router = useRouter()

const { proxy } = getCurrentInstance()

const couponsList = ref([])
const couponProductList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedCouponProduct = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    couponName: null,
    scopeType: null,
    status: null,
  },
  rules: {
    activityName: [
      { required: true, message: "活动名称不能为空", trigger: "blur" }
    ],
    couponName: [
      { required: true, message: "优惠券名称不能为空", trigger: "blur" }
    ],
    couponType: [
      { required: true, message: "类型：CASH-减免现金，DISCOUNT-打折不能为空", trigger: "change" }
    ],
    activityType: [
      { required: true, message: "活动类型：目前仅支持免费领取不能为空", trigger: "change" }
    ],
    shopShareRatio: [
      { required: true, message: "店铺承担比例不能为空", trigger: "blur" }
    ],
    consumeThreshold: [
      { required: true, message: "消费门槛不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "有效期开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "有效期结束时间不能为空", trigger: "blur" }
    ],
    scopeType: [
      { required: true, message: "使用范围：ALL-全品类，PRODUCT-指定商品，CATEGORY-部分分类不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态：CREATED-未开始，ACTIVE-进行中，CLOSED-已关闭，EXPIRED-已过期不能为空", trigger: "change" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
    isDeleted: [
      { required: true, message: "逻辑删除不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询优惠券列表 */
function getList() {
  loading.value = true
  listCoupons(queryParams.value).then(response => {
    const now = new Date().getTime()
    const rows = response.rows || []
    const expiredIds = []
    couponsList.value = rows.map(item => {
      if (item.endTime) {
        const end = new Date(item.endTime).getTime()
        if (now > end && item.status !== 'CLOSED') {
          expiredIds.push(item.id)
          return { ...item, status: 'CLOSED' }
        }
      }
      return item
    })
    total.value = response.total
    loading.value = false
    // 后台同步：把过期的优惠券置为CLOSED
    expiredIds.forEach(id => {
      const target = rows.find(r => r.id === id)
      if (target) {
        updateCoupons({ ...target, status: 'CLOSED' })
      }
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    activityName: null,
    couponName: null,
    couponType: null,
    amount: null,
    activityType: null,
    shopShareRatio: null,
    issueCount: null,
    takeLimit: null,
    scopeDesc: null,
    consumeThreshold: null,
    startTime: null,
    endTime: null,
    scopeType: null,
    status: null,
    createTime: null,
    updateTime: null,
    isDeleted: null,
    receivedCount: null
  }
  couponProductList.value = []
  proxy.resetForm("couponsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  router.push({ path: '/coupon/coupondetail', query: { id: 'new' } })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCoupons(_id).then(response => {
    form.value = response.data
    couponProductList.value = response.data.couponProductList
    open.value = true
    title.value = "修改优惠券"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponsRef"].validate(valid => {
    if (valid) {
      form.value.couponProductList = couponProductList.value
      if (form.value.id != null) {
        updateCoupons(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCoupons(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除优惠券编号为"' + _ids + '"的数据项？').then(function() {
    return delCoupons(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 优惠券-商品关联（scope_type=PRODUCT时生效）序号 */
function rowCouponProductIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 优惠券-商品关联（scope_type=PRODUCT时生效）添加按钮操作 */
function handleAddCouponProduct() {
  let obj = {}
  couponProductList.value.push(obj)
}

/** 优惠券-商品关联（scope_type=PRODUCT时生效）删除按钮操作 */
function handleDeleteCouponProduct() {
  if (checkedCouponProduct.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的优惠券-商品关联（scope_type=PRODUCT时生效）数据")
  } else {
    const couponProducts = couponProductList.value
    const checkedCouponProducts = checkedCouponProduct.value
    couponProductList.value = couponProducts.filter(function(item) {
      return checkedCouponProducts.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleCouponProductSelectionChange(selection) {
  checkedCouponProduct.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coupon/coupons/export', {
    ...queryParams.value
  }, `coupons_${new Date().getTime()}.xlsx`)
}

function handleView(row){
  router.push({ path: '/coupon/coupondetail', query: { id: row.id } })
}

function handleReceiveRecord(row){
  router.push({ path: '/coupon/couponRecord', query: { couponId: row.id } })
}

function handleAllReceiveRecord(){
  router.push({ path: '/coupon/couponRecord' })
}

function handleClose(row){
  const payload = { ...row, status: 'CLOSED' }
  proxy.$modal.confirm('确认关闭该优惠券吗？').then(()=>{
    return updateCoupons(payload)
  }).then(()=>{
    proxy.$modal.msgSuccess('关闭成功')
    getList()
  }).catch(()=>{})
}

function getStatusText(status) {
  const statusMap = {
    'CREATED': '未开始',
    'ACTIVE': '进行中', 
    'CLOSED': '已关闭',
    'EXPIRED': '已过期'
  }
  return statusMap[status] || status
}

function getStatusType(status) {
  const typeMap = {
    'CREATED': 'info',
    'ACTIVE': 'success',
    'CLOSED': 'danger', 
    'EXPIRED': 'warning'
  }
  return typeMap[status] || 'info'
}

getList()
</script>
